package com.sun.springbootfiledownload.controller;

import com.sun.springbootfiledownload.service.FileQueueService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @version 1.0
 * @Package: com.sun.springbootfiledownload.controller
 * @ClassName: FileQueueController
 * @Author: sgq
 * @Date: 2025/4/11 11:25
 * @Description: TODD
 */
@Slf4j
@RestController
@RequestMapping("/api/queue/upload")
public class FileQueueController {

    @Autowired
    private FileQueueService fileQueueService;

    // 存储任务状态（实际项目建议用Redis）
    private final Map<String, TaskStatus> taskStatusMap = new ConcurrentHashMap<>();

    /**
     * 提交文件到上传队列
     * @param file 上传的文件
     * @param folder 目标文件夹
     * @return 任务ID和状态
     */
    @PostMapping("/submit")
    public ResponseEntity<Map<String, Object>> submitUploadTask(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "folder", defaultValue = "default") String folder) {

        // 生成唯一任务ID
        String taskId = "task-" + UUID.randomUUID().toString().substring(0, 8);
        log.info("收到上传请求, 任务ID: {}", taskId);

        // 记录任务为等待状态
        taskStatusMap.put(taskId, new TaskStatus("WAITING", 0, null,""));

        try {
            // 提交到队列（异步执行）
            fileQueueService.addUploadTask(
                    new FileQueueService.FileTask(
                            file,
                            folder,
                            new CompletableFuture<>() {
                                @Override
                                public boolean complete(Object value) {
                                    taskStatusMap.get(taskId).setStatus("COMPLETED");
                                    taskStatusMap.get(taskId).setResultUrl(value.toString());
                                    return super.complete(value);
                                }

                                @Override
                                public boolean completeExceptionally(Throwable ex) {
                                    taskStatusMap.get(taskId).setStatus("FAILED");
                                    taskStatusMap.get(taskId).setErrorMessage(ex.getMessage());
                                    return super.completeExceptionally(ex);
                                }
                            }
                    )
            );

            // 更新为排队状态
            taskStatusMap.get(taskId).setStatus("QUEUED");

            return ResponseEntity.ok(Map.of(
                    "taskId", taskId,
                    "status", "QUEUED",
                    "message", "任务已加入队列"
            ));
        } catch (Exception e) {
            taskStatusMap.get(taskId).setStatus("REJECTED");
            return ResponseEntity.badRequest().body(Map.of(
                    "error", "任务提交失败",
                    "reason", e.getMessage()
            ));
        }
    }

    /**
     * 查询任务状态
     * @param taskId 任务ID
     */
    @GetMapping("/status/{taskId}")
    public ResponseEntity<TaskStatus> getTaskStatus(
            @PathVariable String taskId) {
        TaskStatus status = taskStatusMap.get(taskId);
        if (status == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(status);
    }

    /**
     * 获取已上传文件URL
     * @param taskId 已完成的任务ID
     */
    @GetMapping("/result/{taskId}")
    public ResponseEntity<Map<String, String>> getUploadResult(
            @PathVariable String taskId) {
        TaskStatus status = taskStatusMap.get(taskId);
        if (status == null || !"COMPLETED".equals(status.getStatus())) {
            return ResponseEntity.badRequest().body(Map.of(
                    "error", "任务未完成或不存在"
            ));
        }
        return ResponseEntity.ok(Map.of(
                "url", status.getResultUrl()
        ));
    }

    /**
     * 任务状态内部类
     */
    @Data
    @AllArgsConstructor
    private static class TaskStatus {
        private String status;  // WAITING/QUEUED/PROCESSING/COMPLETED/FAILED
        private int progress;   // 进度百分比
        private String resultUrl; // 完成后的文件URL
        private String errorMessage; // 失败信息
    }
}